<template>
  <div class="signature">
    <canvas
      ref="canvas"
      @touchstart="startDrawing"
      @touchmove="draw"
      @touchend="stopDrawing"
    ></canvas>
    <div class="btns">
      <button @click="clear">清空</button>
      <button @click="save">确定</button>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      canvas: null,
      ctx: null,
      drawing: false,
      signatureData: null
    }
  },
  mounted () {
    this.canvas = this.$refs.canvas
    this.ctx = this.canvas.getContext('2d')
  },
  methods: {
    startDrawing (e) {
      this.drawing = true
      const rect = this.canvas.getBoundingClientRect()
      const touch = e.touches[0]
      this.ctx.beginPath()
      this.ctx.moveTo(touch.clientX - rect.left, touch.clientY - rect.top)
    },
    draw (e) {
      if (!this.drawing) return
      const rect = this.canvas.getBoundingClientRect()
      const touch = e.touches[0]
      this.ctx.lineTo(touch.clientX - rect.left, touch.clientY - rect.top)
      this.ctx.stroke()
    },
    stopDrawing () {
      this.drawing = false
    },
    clear () {
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
      this.signatureData = ''
      this.$emit('clear')
    },
    save () {
      this.signatureData = this.canvas.toDataURL()
      this.$emit('done', this.signatureData)
    }
  }
}
</script>

<style lang="scss" scoped>
.btns {
  float: right;
}
</style>
